/*
 * @author Chris
 * @since 2023/2/2 22:06
 *
 * @brief    The project will ...
 *
 * @note     ...
 *
 * @warning  Do not to ...
 *
 * Change Logs:
 *   Date           Author       Notes
 *   2023/2/2     Chris        the first version
 */
#include "8052.h"

extern void I2CStart();

extern __sbit I2CWrite(unsigned char dat);

extern unsigned char I2CReadAck();

extern unsigned char I2CReadNack();

extern void I2CStop();

void E2Read(unsigned char *buf, unsigned char addr, unsigned char len) {
    do {
        I2CStart();
        if (I2CWrite(0x50 << 1)) {
            break;
        }
        I2CStop();
    } while (1);

    I2CWrite(addr);
    I2CStart();
    I2CWrite((0x50 << 1) | 1);
    while (len-- > 1) {
        *buf++ = I2CReadAck();
    }

    *buf = I2CReadNack();
    I2CStop();
}

void E2Write(unsigned char *buf, unsigned char addr, unsigned char len) {
    while (len > 0) {
        do {
            I2CStart();
            if (I2CWrite(0x50 << 1)) {
                break;
            }
            I2CStop();
        } while (1);

        I2CWrite(addr);
        while (len-- > 0) {
            I2CWrite(*buf++);
            addr++;
            if ((addr & 0x07) == 0) {
                break;
            }
        }

        I2CStop();
    }
}